#include <57header.h>

long long current_time_millis() {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts); // 获取当前时间
    return (long long)ts.tv_sec * 1000LL + ts.tv_nsec / 1000000; // 转换为毫秒
}

/* Usage: ./copy src dest */
void copy_file(const char *src, const char *dest) {
    FILE *src_fp = fopen(src, "rb");       // b在Linux平台下加不加都无所谓
    //if (src_fp == NULL) {
    //    // 将参数拼到当前errno的错误信息上
    //    perror("fopen src");
    //    exit(1);
    //}
    ERROR_CHECK(src_fp, NULL, "fopen");

    FILE *dest_fp = fopen(dest, "wb");
    if (dest_fp == NULL) {
        perror("fopen dest");
        fclose(src_fp);  // 关闭已打开的源文件
        exit(1);
    }

    // 用于临时存储数据的中转站
    char buf[1024] = { 0 }; 
    size_t count;

    // 从源文件读取数据并写入目标文件
    while ((count = fread(buf, 1, sizeof(buf), src_fp)) > 0) {
        fwrite(buf, 1, count, dest_fp);
    }

    // 关闭文件流
    fclose(src_fp);
    fclose(dest_fp);
}

int main(int argc, char *argv[]) {
    //if (argc != 3) {
    //    fprintf(stderr, "args error!\n");
    //    exit(1);
    //}
    long long t1 = current_time_millis();
    ARGS_CHECK(argc, 3);
    copy_file(argv[1], argv[2]);
    long long t2 = current_time_millis();
    printf("time = %lld\n", (t2 - t1));
    return 0;
}
